/*
 * Copyright (c) 2021
 * User:mallplus多商户商城
 * File:QiNiuUtil.java
 * Date:2021/01/12 19:29:12
 */

package com.qyine.rlmall.utils;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qyine.rlmall.sys.entity.SysQiniuConfig;
import lombok.extern.slf4j.Slf4j;

import java.io.File;

/**
 * 七牛云工具
 *
 * @author Zero
 * @date 2019-05-28
 */
@Slf4j
public class QiNiuUtil {


    /**
     * 七牛云上传文件
     *
     * @param file     文件地址
     * @param fileName 文件名
     * @return 返回结果
     */
    public static String fileUpload(File file, String fileName, SysQiniuConfig config) {
        //构造一个带指定Zone对象的配置类
        Configuration cfg;
        cfg = new Configuration(Zone.zone0());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = "file/" + System.currentTimeMillis();
        Auth auth = Auth.create(config.getAccessKey(), config.getSecretKey());
        String upToken = auth.uploadToken(config.getBucket());
        String result;
        try {
            Response response = uploadManager.put(file, key + fileName, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            log.info("{七牛文件上传key: " + putRet.key + ",七牛excel文件传hash: " + putRet.hash + "}");
            result = config.getHost() + putRet.key;
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
            result = null;
        }
        return result;
    }

}
